function [likel,ssvec,flag_ok,lht]=likelNanSplit(parest,parvec,parposest,funcmod,Y,trainvec,solveopt,addsol)
% =========================================================================
%% LikelNanSplit.m
%
% This code estimates the likelihood of a NaN model (without cummulators),
% with Split Solutions, where all matrices (GG,RR,C,SDX,ZZ) are allowed to change in the second part of
% the sample at a timne T*
%
%% *Additional inputs needed*
% *addsol.dateBegSecond*  Numeric Calendar date when second sample begins
% (provided in settings)
% *addsol.rowBegSecond*  Position in the sample vector where second sample
% begins (computed in LMJ_initial.m)
%
% Matrices of the second sample are given in the structure second, usually
% called FLAG, in the solution of the model, e.g.
%
% [GG, RR, CONS, eu, SDX, ZZ, initss, ssvec, flag, ssnames]=feval(funcmod,param,options,addsol);
%
% =========================================================================
%% Initialize parameters
likel=-1e20; flag_ok=0;
parvec(parposest)=parest;
%% Model solution, second sample stored in structure second (second sample)
[G,R,C,eu,SDX,Z,structOne,ssvec,structTwo]=feval(funcmod,parvec,solveopt,addsol);

[T,ny] = size(Y);
%% Demeaning using the split sample
%  First Sample (C1)
if any(C~=0)==1
    Y(1:addsol.rowBegSecond-1,:)=...
        Y(1:addsol.rowBegSecond-1,:)-repmat((Z*C)',[addsol.rowBegSecond-1 1]);
end
% Second sample (second.second.C)
if any(structOne.C~=0)==1;
    Y(addsol.rowBegSecond:end,:)=...
        Y(addsol.rowBegSecond:end,:)-repmat((structOne.Z*structOne.C)',[(T-addsol.rowBegSecond+1) 1]);
end
Y=Y';
%% Initialization of the State and Co-variance of the state

pshat=lyapunov_symm(G,R*(SDX')*(R*(SDX')'));
shat        =  zeros(size(G,1),1);

%% Forward Filter

% Storage matrices
lht         =  zeros(T,1);
Zdim        =  zeros(T,1); 
W           =  eye(ny);

% Filter, first part
for ii=1:addsol.rowBegSecond-1;
    
    % Handling of missing observations 
    ytt=Y(:,ii);
    
    % Determine W and position of the NAN  
    ind =~isnan(ytt);
    
    ytt=ytt(ind);    
    Zdim(ii)=length(ytt); 
    Ztt=W((ind==1),:)*Z;
    
    [shat,pshat,lht(ii)]=feval(@kf,ytt,Ztt,shat,pshat,G,R*(SDX'));
end

% Filter, second part
for ii=addsol.rowBegSecond:T;
    
    % Handling of missing observations 
    ytt=Y(:,ii);
    
    % Determine W and position of the NAN  
    ind =~isnan(ytt);
    
    ytt=ytt(ind);    
    Zdim(ii)=length(ytt); 
    Ztt=W((ind==1),:)*structOne.Z;
    
    [shat,pshat,lht(ii)]=...
        feval(@kf,ytt,Ztt,shat,pshat,structOne.G,(structOne.R)*(structOne.SDX'));
end

%% Likelihood plus integration constant

lht=lht(trainvec(1):trainvec(2));
likel=-0.5*length(lht)*log(2*pi)*(sum(Zdim)) + sum(lht);
flag_ok=1;

%% End of File
end